package com.example.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.cloud.consul.discovery.HeartbeatProperties;
import org.springframework.cloud.consul.discovery.TtlScheduler;
import org.springframework.cloud.consul.serviceregistry.ConsulRegistration;
import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry;
import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistryAutoConfiguration;
import org.springframework.context.annotation.Configuration;

import com.ecwid.consul.v1.ConsulClient;

@Configuration
public class UserConsulServiceRegistryAutoConfiguration extends ConsulServiceRegistryAutoConfiguration {
	@Value("${version}")
	private String version;

	@Override
	public ConsulServiceRegistry consulServiceRegistry(ConsulClient consulClient, ConsulDiscoveryProperties properties,
			HeartbeatProperties heartbeatProperties, @Autowired(required = false) TtlScheduler ttlScheduler) {
		return new ConsulServiceRegistry(consulClient, properties, ttlScheduler, heartbeatProperties) {
			@Override
			public void register(ConsulRegistration reg) {
				reg.getService()
						.setId(new StringBuilder(reg.getService().getName()).append("-")
								.append(reg.getService().getAddress()).append("-").append(reg.getService().getPort())
								.append("-").append(version).toString());
				super.register(reg);
			}
		};
	}

}
